"""
    Usage:
            setrefid  [--help] [-h] [--inputDir=DIR] [-i DIR]
                      [--temporaryDir=DIR] [-t DIR]
                      [--outputDir=DIR] [-o DIR]
                      [--renameFile] [-r] [--printDefults] [-p] [XML file(s)]

        --inputDir      Directory from which to read input files.
        -i

        --temporaryDir  Directory in which to store intermediate files duing creation.
        -t
        
        --outputDir     Directory used as delivery point to master system.
        -o

        --renameFile    Should the inputfile also be renamed during processing?
        -r              Defaults to false.
        
        --help          Displays this help page.
        -h

        --printDefults  Print default values and exit
        -p

    Author Anders Sodergrann, 06.09.2010.

"""
import os.path
import xml.dom.minidom
import sys
import getopt
import csv
import logging
import time
import platform
import shutil
import os

LOG_FILENAME = os.path.join( "..", "tmp", "SETREFID.py." + time.strftime("%Y%m%d", time.localtime() ) + ".dbg" )
#LOG_LEVEL=logging.DEBUG
LOG_LEVEL=logging.INFO

TRANSACTION_COUNT_FILE = os.path.join( os.path.dirname( os.path.abspath( sys.argv[0] ) ), "inTransactionCounter.dat" )

OPTION_RENAME_FILE=False



def moveOriginalFile( inputFile, inputDir ):

    ayOhError = False
    source = os.path.join( os.path.abspath(inputDir), inputFile )
    target = os.path.join( os.path.join( os.path.dirname(os.path.abspath(inputDir)), "log", inputFile ) )
    
    try:
        shutil.move( source, target )
    except IOError:
        logging.error( "Failed to move XML file %s to log dir." %inputFile )
        logging.error( "    source [" + source + "] target [" + target + "]." )
        ayOhError = True
        pass

    moveSucceeded = ( not ayOhError )

    return moveSucceeded




def copyOriginalFile( inputFile, inputDir ):

    ayOhError = False
    source = os.path.join( os.path.abspath(inputDir), inputFile )
    target = os.path.join( os.path.join( os.path.dirname(os.path.abspath(inputDir)), "log", inputFile ) )

    try:
        shutil.copy( source, target )
    except IOError:
        logging.error( "Failed to copy XML file %s to log dir." %inputFile )
        logging.error( "    source [" + source + "] target [" + target + "]." )
        ayOhError = True
        pass

    copySucceeded = ( not ayOhError )

    return copySucceeded


def deleteOriginalFile( inputFile, inputDir ):

    ayOhError = False
    source = os.path.join( os.path.abspath(inputDir), inputFile )

    try:
        os.remove( source )
    except IOError:
        logging.error( "Failed to delete XML file %s ." %inputFile )
        ayOhError = True
        pass

    deleteSucceeded = ( not ayOhError )

    return deleteSucceeded


def getNextTransactionNumberAndUpdate( transactionCountFile ):

    transactionNumber = 0
    returnValue = 0

    try:
        transactionCountFileExists = os.path.exists( transactionCountFile )
        
        if transactionCountFileExists :
            
            transCntHandle = open( transactionCountFile, 'r+' )
            nextCountString = transCntHandle.readline()
            settingSplit = str.split( nextCountString, "=" )

            if ( settingSplit[0] == "NextTransactionNumber" ) and ( len( settingSplit ) == 2 ) :
                transactionNumber = long( settingSplit[1] )
            transCntHandle.seek(0)

        else:

            transCntHandle = open( transactionCountFile, 'w' )

        returnValue = transactionNumber

        if transactionNumber > 999999998 :
            transactionNumber = 0
        else:
            transactionNumber += 1

        nextCountString = "NextTransactionNumber=%ld\n" % transactionNumber
        transCntHandle.write( nextCountString )
        transCntHandle.close()
        
    except IOError:
        logging.error( "Failed to r/w %s file. Aborting." %transactionCountFile )
        sys.exit(1)
        
    return returnValue



def replaceIdTag( inFile, outFile ):

    refIdFound = False
    searchId = False

    inputFile = open( inFile, "r" )
    outputFile = open( outFile, "w" )

    for row in inputFile:
        newRow = row
        if searchId:
            if "<Id>" in row:
                if "</Id>" in row:
                    #print row
                    tags = row.split(">")
                    #print tags
                    ids = (tags[1]).split("<")
                    #print ids
                    newTransNumber = "%ld" % getNextTransactionNumberAndUpdate( TRANSACTION_COUNT_FILE )
                    newRow = tags[0] + ">" + newTransNumber + "<" + ids[1] + ">" + tags[2]
                    searchId = False
        print newRow
        outputFile.write( newRow )

        if "<RefId>" in row:
            refIdFound = True
            searchId = True

    inputFile.close()
    outputFile.close()

    return refIdFound

# end replaceIdTag()



def processXMLfile( inFile, tempDir, inputDir, outputDir ):

    if os.path.isfile( inFile ): # Was filename provided during script exec?
        inputFile = inFile
        outputFile = os.path.join( outputDir, os.path.basename( inFile ) )
    else:
        inputFile = os.path.join( inputDir, os.path.basename( inFile ) )
        outputFile = os.path.join( outputDir, os.path.basename( inFile ) )

    print "Input  " + inputFile
    print "Output " + outputFile
    sys.exit(0)

    fileName = "EmWsSync9430.xml"
    outFilename = "utfil.xml"

    inputFile = ""
    outputFile = ""
    
    return replaceIdTag( inputFile, outputFile )




def main():

    logging.basicConfig(filename=LOG_FILENAME,level=LOG_LEVEL)
    #logging.setFormatter( logging.Formatter("%(name)s : %(asctime)s : %(levelname)s : %(message)s") )

    timeString = time.strftime("%Y-%m-%d %H:%M:%S %Z", time.localtime() )
    logging.info('--- Startup at %s ---' %timeString )
    logging.info( "Executing on " + platform.system() )
    logging.debug( "Called using " + str( sys.argv[0:] ) )
    
    inputDir = os.path.join( "..", "net", "rename", "convert" )
    tempDir = os.path.join( "..", "tmp" )
    outputDir = os.path.join( "..", "net", "xmlin", "xmlrcv" )
    inputFile = os.path.join( inputDir, "EmployeeWorkScheduleSync_20100629.csv" )
    
    # parse command line options
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hi:t:o:rp", ["help","inputDir=","temporaryDir=","outputDir=","renameFile", "printDefults"])
    except getopt.error, msg:
        print msg
        print "for help use --help"
        sys.exit(2)

    # process options
    for o, a in opts:
        if o in ("-h", "--help"):
            print __doc__
            sys.exit(0)
        if o in ("-i", "--inputDir"):
            inputDir = a
        if o in ("-t", "--temporaryDir"):
            tempDir = a
        if o in ("-o", "--outputDir"):
            outputDir = a
        if o in ("-r", "--renameFile"):
            OPTION_RENAME_FILE=True
        if o in ("-p", "--printDefults"):
            print __doc__
            print " Default settings:"
            print "   inputDir=%s" % inputDir
            print "    tempDir=%s" % tempDir
            print "  outputDir=%s\n" % outputDir
            sys.exit(0)

    logging.info( "Script called is " + sys.argv[0] )
    logging.info( "Using inputDir=" + inputDir )
    logging.info( "Using tempDir=" + tempDir )
    logging.info( "Using outputDir=" + outputDir )

    # process arguments
    if len( args ) == 0 :
        if os.path.exists( inputDir ) :
            dirList = os.listdir( os.path.abspath( inputDir ) )
        else:
            dirList = os.listdir( os.path.dirname( os.path.abspath( sys.argv[0] ) ) )

        for fileInDir in dirList:
            if os.path.isfile( fileInDir ) :
                fileParts = fileInDir.split(".")
                if (fileParts[ len( fileParts ) - 1 ]).lower() == "xml" :
                    args.append( fileInDir )

    for arg in args:
        processXMLfile( arg, tempDir, inputDir, outputDir )

    timeString = time.strftime("%Y-%m-%d %H:%M:%S %Z", time.localtime() )
    logging.info('--- Shutdown at %s ---' %timeString )

#if __name__ == "__main__":
main()


